# -*- coding:UTF-8 -*-
"""
DataChain 的发行中心和结算中心
"""

from flask import Flask,render_template,request
import dbopt
import DataChain
import hashlib
import json
from urllib import parse
from urllib import request as req
import base64
import re
from gevent import monkey
from gevent.pywsgi import WSGIServer
import logging

monkey.patch_all()



app = Flask(__name__)
app.config.update(DEBUG=True)

def cal_data_list():
    db = dbopt.dbopt()
    data = db.findall_data()
    chain = DataChain.DataChain(data)
    data_re = []
    for x in chain.Chain:
        data_re.append(x.get_data())
    return data_re



@app.route('/')
def index():
    return render_template('index.html',name = "嫣嫣")

@app.route('/login')
def login():
    return render_template('login.html')

@app.route('/baidu')
def baidu():
    return render_template('baiduwenku.html',fenshu = "未知")

@app.route('/baidu',methods=['post'])
def baidu_post():
    url = request.form.get('url')
    ret = get_doc(url)
    if re.search('----',ret.decode())!= None :
        dw = ret.decode().split('----')
        dw_point = dw[1]
        dw_url = base64.b64decode(dw[0]).decode()
        dw_url_s = dw_url.split("filename")
        filename = parse.unquote(parse.unquote(dw_url_s[1]))[2:-3]
        print("下载了文件："+filename)
        app.logger.info("下载了文件："+filename)
        return render_template('baiduwenku.html', fenshu=dw_point, down_url=dw_url, filename=filename)
    else:
        return render_template('baiduwenku.html', fenshu="未知", error= ret)
def get_doc(url):
    a = parse.urlparse(url)
    file = a.path[6:-5]
    post_d = {'usrname':'bgcjuj',
                'usrpass':'ywynh',
                'docinfo':file,
                'taskid':'up_down_doc'}
    post_url = 'http://www.blpack.com/post.php'
    post_data = parse.urlencode(post_d).encode("utf-8")
    f = req.Request(post_url,post_data)
    req_data = req.urlopen(f)
    return req_data.read()
@app.route('/get_data')
def get_data():
    data_s = cal_data_list()
    data_json = json.dumps(data_s)
    return data_json

if __name__ == '__main__':
    handler = logging.FileHandler('flask.log')
    app.logger.addHandler(handler)
    http_server = WSGIServer(('0.0.0.0', 8080), app)
    http_server.serve_forever()